#include "broker.h"

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

struct bcshm_t shm;
struct bcshmseg_t shmseg;

void reader(){
  
  while(1){
    bcshm_read(SHM_EVENT, &shm, &shmseg.event);
    bcshm_read(SHM_ABORT, &shm, &shmseg.abort);
    bcshm_read(SHM_FCACTION, &shm, &shmseg.fc_action);
    bcshm_read(SHM_FLIGHT_TASK, &shm, &shmseg.flight_task);
    bcshm_read(SHM_FTC_TLM, &shm, &shmseg.ftc_tlm);
    bcshm_read(SHM_FC_TLM, &shm, &shmseg.fc_tlm);

    gcs_tlm_t gcs_tlm = {.ftc_tlm = shmseg.ftc_tlm, .fc_tlm = shmseg.fc_tlm};

    printf("Shared memory.\n");

    printf("\tEvent: %d\n", (int)shmseg.event);
    printf("\tAbort: %d\n", (int)shmseg.abort);
    printf("\tAction (FC): %d\n", (int)shmseg.fc_action);

    printf("\tFlight task:\n");
    printf("\t\tHight: %d\n", (int)shmseg.flight_task.hight);
    printf("\t\tStart time: %d\n", (int)shmseg.flight_task.start_time);
    printf("\t\tHang time: %d\n", (int)shmseg.flight_task.hang_time);

    gcs_tlm_print(gcs_tlm);
    printf("*******************************************************\n");

    usleep(1e6 / 2);
  }
}

void tester(){
  FILE* fp;
  fp = fopen("/dev/shm/bcshm", "rb");
  int count = fread(&shmseg, sizeof(shmseg), 1, fp);
  printf(">%d\n", count);
  printf("%d\n", (int)shmseg.event);
  printf("%f\n", shmseg.fc_tlm.hight);
  printf("%f\n", shmseg.fc_tlm.speed);
}

int main(int argc, char* argv[]) {

  //bcshm_delete();
  //bcshm_init();
  bcshm_open(&shm);

  //EVENT_t ev = EVENT_UNKNOWN;
  //bcshm_write(SHM_EVENT, &shm, &ev);
  
  reader();
  //tester();
  
  bcshm_close(&shm);
  return 0;
}
